package com.example.wm.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;


import com.example.wm.service.impls.OCRService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/ocr")
public class OCRController {
    @Value("${upload.path}")
    private String uploadPath;
    @Autowired
    private OCRService ocrService;
    @PostMapping("/extract-text2")
    public ResponseEntity<String> extractTextFromImage2(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("未选择图片!", HttpStatus.BAD_REQUEST);
        }

        try {
            // 将 MultipartFile 转换为 File
            File imageFile = convertMultiPartToFile(file);
            String result = ocrService.extractTextFromImage(imageFile);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件处理错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Transactional
    @PostMapping("/extract-text")
    public Result extractTextFromImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultData.error(403,"未上传文件");
        }


        try {
            //保存文件
//           String imgurl= saveFile(file);
//           System.out.println(imgurl);
            //请求本地服务器
            HashMap result=  requestorc(file);

            return ResultData.success("提取成功",result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error(403,"文件处理错误");
        }
    }
    //保存图片地址
    @PostMapping("/saveFile")
    public  Result saveFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResultData.error(304,"文件为空，请选择一张图片上传");
        }

        // 确保上传目录存在
//        String uploadDir="D:\\work\\img";
        File dir = new File(uploadPath);
        Path uploadDirs = Paths.get(uploadPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 压缩后的文件路径
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return  ResultData.error(304,"文件名无效");
        }
        String compressedFilename = "compressed_" + originalFilename;
        Path compressedFile = uploadDirs.resolve(compressedFilename);

        // 压缩图片并保存到本地
//        try (java.io.InputStream is = file.getInputStream()) {
//            Thumbnails.of(is)
//                    .size(800, 800) // 设置压缩后的图片尺寸
//                    .outputQuality(0.8) // 设置压缩后的图片质量（0.0 - 1.0）
//                    .toFile(compressedFile.toString());
//        }
//        String urlimg="http://127.0.0.1:8020/"+compressedFile.getFileName();
//        http://127.0.0.1:8020/ compressed_ZfOjoL4pMpvK8924bd7766f75f7f1149c9718217c5d3.jpg
        return ResultData.success(compressedFilename);
    }
    @PostMapping("/deleteimg")
    private Result deleteimg(@RequestBody List<String> list) throws MalformedURLException {
        boolean allDeleted = true;
        StringBuilder errorMessages = new StringBuilder();
        for (String s : list) {
            URL url = new URL(s);
            String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);
            System.out.println( fileName+"fileName" );
            File file = new File(uploadPath, fileName);

            if (file.exists()) {
                if (!file.delete()) {
                    allDeleted = false;
                    errorMessages.append("文件 ").append(fileName).append(" 删除失败; ");
                }
            } else {
                allDeleted = false;
                errorMessages.append("文件 ").append(fileName).append(" 不存在; ");
            }
        }

        if (allDeleted) {
            return ResultData.success("所有文件删除成功");
        } else {
            return ResultData.error(304, errorMessages.toString());
        }
    }
    @PostMapping("/deleteimg2")
    public Result deleteImages2(List<String> list) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<List<String>> request = new HttpEntity<>(list, headers);
        RestTemplate restTemplate = new RestTemplate();

        // 发送 POST 请求
        String response = restTemplate.postForObject("http://118.31.75.80:8090/ocr/deleteimg", request, String.class);

        // 处理响应
        if (response != null) {
            System.out.println("服务器响应: " + response);
            return ResultData.success(response);
        } else {
            System.out.println("没有收到服务器响应");
            return ResultData.error(304,"删除失败");
        }
    }
    @GetMapping("/{filename}")
    public ResponseEntity<byte[]> getImage(@PathVariable String filename) {
        try {
            // 构建文件路径
            File file = new File(uploadPath, filename);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 读取文件内容
            byte[] imageContent = new byte[(int) file.length()];
            try (FileInputStream fis = new FileInputStream(file)) {
                fis.read(imageContent);
            }

            // 返回文件内容
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG) // 根据文件类型设置 MIME 类型
                    .body(imageContent);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    //请求服务器
    private HashMap<String, String> requestorc(MultipartFile file){
        byte[] ss=null;
        String base64EncodedString=null;
        try{
            ss = file.getBytes();
            base64EncodedString = Base64.getEncoder().encodeToString(ss);

        }catch(IOException e){
            e.printStackTrace();
        }
        String re=base64EncodedString;
        RestTemplate restTemplate = new RestTemplate();
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = MediaType.parseMediaType("application/json;charset=GBK");
        headers.setContentType(mediaType);
        HttpEntity<String> request = new HttpEntity<>(re, headers);
        String url="http://47.115.29.137:19811/ocr_data_1";
        String response = restTemplate.postForObject(url, request, String.class);
        String  ress= togbk(response);

        String roleName = extractValue(ress, "角色名称", "角色编号");
        String roleNumber = extractValue(ress, "角色编号", "服务器");
        String server = extractValue(ress, "服务器", "区");
        String gameZone = extractValue(ress, "区", "赛");

//         System.out.println("角色名称: " + roleName);
//         System.out.println("角色编号: " + roleNumber);
//         System.out.println("服务器: " + server);
//         System.out.println("赛区: " + gameZone);
        HashMap<String,String> hs=new HashMap<>();
        hs.put("角色名称",roleName);
        hs.put("角色编号",roleNumber);
        hs.put("服务器",server);
        hs.put("赛区",gameZone);

//         System.out.println("Response: " + hs);
        return hs;
    }
    public String togbk (String args) {
        String originalString = args;

        try {
            // 将字符串编码为 GBK
            byte[] gbkBytes = originalString.getBytes(StandardCharsets.ISO_8859_1);
            // 可以将字节数组转换回字符串进行显示，注意这只是为了展示效果
            String convertedString = new String(gbkBytes, "GBK");
            System.out.println("Original String: " + originalString);
            System.out.println("GBK Encoded Bytes: " + java.util.Arrays.toString(gbkBytes));
            System.out.println("Converted Back String: " + convertedString);
            return convertedString;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private static String extractValue(String input, String startDelimiter, String endDelimiter) {
        int startIndex = input.indexOf(startDelimiter) + startDelimiter.length();
        int endIndex = input.indexOf(endDelimiter, startIndex);

        if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
            return input.substring(startIndex, endIndex).trim();
        }
        return "";
    }



    private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
        file.transferTo(convFile);
        return convFile;
    }
}
